from flask import request

from zvms.util import *

User = Blueprint('User', __name__)

LoginForm = Form(
    id=[Int],
    pwd=[Required]
)

@User.route('/login', None, methods=['GET', 'POST'])
def login():
    if LoginForm.validate_on_submit():
        id = int(request.form.get('id'))
        res = post('/user/login', id=id, pwd=md5ify(request.form.get('pwd')))
        if res:
            res = res['result']
            session['token'] = res['token']
            session['id'] = id
            res = get(f'/user/{request.form.get("id")}')['result']
            session['name'] = res['name']
            session['auth'] = res['auth']
            session['cls'] = res['cls']
            session['clsName'] = res['clsName']
            return redirect('/')
        session['error'] = res['message']
    return render_template('login.html')

@User.route('/logout')
def logout():
    session.pop('token')
    return redirect('/login')

@User.route('/user/<int:id>')
@User.route('/user')
def get_user(id=None):
    if id is None:
        id = session.get('id')
    print(get(f'/user/{id}')['result'])
    return render_template('user.html', **get(f'/user/{id}')['result'])

@User.route('/mod-pwd', methods=['POST'])
def mod_pwd():
    res = post('/user/mod-pwd', old=request.form.get('old'), neo=request.form.get('neo'))
    return res

@User.route('/change-class', 4, methods=['POST'])
def change_class():
    return post('/user/change-class', cls=int(request.form.get('id')))

@User.route('/settings')
def settings():
    return render_template('settings.html')